package com.tbit.main.controller.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.tbit.common.utils.RpcSecurityUtil;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.service.AccountUserFreeLoginService;
import com.tbit.main.service.AccountUserService;
import com.tbit.main.service.TokenService;
import com.tbit.main.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.tbit.common.constant.SystemConstant.ACCOUNT_USER_ID;


/**
 * 登录拦截器
 *
 * @author Leon
 * 2019年1月23日 下午3:51:42
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private AccountUserFreeLoginService freeLoginService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (RpcSecurityUtil.authentication(request)) {
            rpcAuth(request);
            return true;
        }
        /*获取token*/
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)){
            token = request.getHeader("token");
        }
        if (token == null) {
            ResponseUtil.print(response, "{\"ret\":0,\"msg\":\"登录已过期，请重新登录\"}");
            log.warn("[LoginInterceptor][url：{}][parameter：{}][token is null]", request.getRequestURI(), JSONUtil.toJsonStr(request.getParameterMap()));
            return false;
        }

        AccountUser accountUser = tokenService.getAccount(token);
        if (accountUser == null) {
            ResponseUtil.print(response, "{\"ret\":0,\"msg\":\"登录已过期，请重新登录\"}");
            String userId = request.getHeader("userId");
            log.warn("[LoginInterceptor][url：{}][parameter：{}][userId: ({})][token: ({}) 失效]", request.getRequestURI(), JSONUtil.toJsonStr(request.getParameterMap()), userId, token);
            return false;
        }
        //过期校验
        accountUserService.expireCheck(accountUser.getAccountUserId());
        //免密登录
        freeLoginService.freeLogin(accountUser.getAccountUserId(), accountUser.getAccountId());
        // 放入登录上下文
        LoginUserContextHolder.setLoginUser(accountUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) {
        // 清空登录用户上下文
        LoginUserContextHolder.removeLoginUser();
    }

    private void rpcAuth(HttpServletRequest request) {
        String accountUserId = request.getHeader(ACCOUNT_USER_ID);
        if (StrUtil.isNotBlank(accountUserId)) {
            AccountUser accountUser = accountUserService.getAccountUserById(Integer.valueOf(accountUserId));
            accountUser.buildAccountUserType();
            LoginUserContextHolder.setLoginUser(accountUser);
        }
    }
}
